package weibo

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/gocolly/colly/v2"
)

type Remain struct {
	Ok       int `json:"ok"`
	Statuses []struct {
		Source  string `json:"source"`
		Textraw string `json:"text_raw"`
		Cat     string `json:"created_at"`
		User    struct {
			ScreenName string `json:"screen_name"`
		}
		ContinueTag struct {
			Pic string `json:"pic"`
		} `json:"continue_tag"`
		AttitudesCount int `json:"attitudes_count"`
		PageInfo       struct {
		}
	} `json:"statuses"`
	TotalNumber int    `json:"total_number"`
	SinceId     string `json:"since_id"`
	MaxId       int    `json:"max_id"`
}

var (
	f    *os.File
	Lock sync.RWMutex
	Path string
)

func SetSavePath() {
	var err error
	f, err = os.OpenFile(Path+"/now.csv", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("打开文件错误")
		err = os.MkdirAll(Path, 0755)
		if err != nil {
			fmt.Println("MkdirAll--->", err)
		}
		f, err = os.OpenFile(Path+"/now.csv", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	}
}

func Jx() {
	for _, card := range Data.Statuses {
		pname := card.User.ScreenName
		fmt.Println(pname)
		//text := card.Mblog.Text
		text := card.Textraw
		image := card.ContinueTag.Pic
		cat := card.Cat
		text = strings.Replace(text, ",", "，", -1)
		alltext := strings.Replace(pname+","+cat+","+image+","+text, "\n", "", -1)
		_, err := f.WriteString(alltext + "\n")
		if err != nil {
			fmt.Println("写入失败!")
			return
		}
	}
}

var Data = Remain{}

func get() {
	c1 := colly.NewCollector()
	c1.OnRequest(func(req *colly.Request) {
		c1.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
		req.Headers.Add("Cookie", "_T_WM=49047619017; XSRF-TOKEN=f6d24e; WEIBOCN_FROM=1110006030; mweibo_short_token=97fa00a8eb; MLOGIN=0; M_WEIBOCN_PARAMS=uicode%3D20000174")
		req.Headers.Add("Referer", "https://m.weibo.cn/")
	})
	c1.OnResponse(func(res *colly.Response) {
		fmt.Println(time.Now().Unix())
		//fmt.Println(string(res.Body))
		err := json.Unmarshal(res.Body, &Data)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer func() {
			fmt.Println("重置Data")
			Data = Remain{}
		}()
		if Data.Ok == 1 {
			fmt.Println(Data.Statuses[0].User.ScreenName, "------> 1")
			Jx()
		}
	})
	c1.OnError(func(res *colly.Response, err error) {
		fmt.Println(err)
	})
	err := c1.Visit("https://weibo.com/ajax/feed/hottimeline?since_id=0&refresh=0&group_id=102803&containerid=102803&extparam=discover%7Cnew_feed&max_id=0&count=10")
	if err != nil {
		return
	}
}
